# -*- coding: utf-8 -*-
# Project : flacon
# File : converter.py
# (c) Alexander Sokolov sokoloff.a@gmail.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

import flacon
from trackset import *
from disc import *

from PyQt4 import QtCore
from PyQt4.QtCore import *

class CueCreator():
   #****************************************************************
   #
   #****************************************************************
    def __init__(self, disc):
        self._disc = disc
        self._textCodec = QTextCodec.codecForName("UTF-8")
        self._file = None
        self._pregapFile = QString()


   #****************************************************************
   #
   #****************************************************************
    def codePage(self):
        return self._textCodec.name()


   #****************************************************************
   #
   #****************************************************************
    def setCodePage(self, value):
        if self.codePage() == value:
            return

        self._textCodec = QTextCodec.codecForName(value)


   #****************************************************************
   #
   #****************************************************************
    def pregapFileName(self):
        return self._pregapFile


   #****************************************************************
   #
   #****************************************************************
    def setPregapFileName(self, value):
        self._pregapFile = value


   #****************************************************************
   #
   #****************************************************************
    def _writeLine(self, line):
        self._file.write(self._textCodec.fromUnicode(line + "\n"));


   #****************************************************************
   #
   #****************************************************************
    def write(self, fileName):
        self._file = QFile(fileName)
        if not self._file.open(QIODevice.WriteOnly | QIODevice.Text):
            raise FileErrorCantWriteCue(fileName)

        tracks = self._disc.tracks()

        firstTrack = tracks[0]

        diskId = tracks.discId()
        genre  = firstTrack.genre()
        year   = firstTrack.year()
        album  = firstTrack.album()
        artist = firstTrack.artist()
        songWriter = firstTrack.songWriter()

        for track in tracks:
            if track.genre()  != firstTrack.genre():   genre = None
            if track.year()   != firstTrack.year():    year = None
            if track.album()  != firstTrack.album():   album = None
            if track.artist() != firstTrack.artist():  artist = None
            if track.songWriter() != firstTrack.songWriter():   songWriter = None


        # Common ...........................
        if tracks.catalog():
            self._writeLine(QString('CATALOG %1').arg(tracks.catalog()))

        if tracks.cdTextFile():
            self._writeLine(QString('CDTEXTFILE "%1"').arg(tracks.cdTextFile()))

        if genre:
            self._writeLine(QString('REM GENRE "%1"').arg(genre))

        if year:
            self._writeLine(QString('REM DATE %1').arg(year))

        if diskId:
            self._writeLine(QString('REM DISCID %1').arg(diskId))

        self._writeLine(QString('REM COMMENT "Flacon v%1"').arg(flacon.FLACON_VERSION))

        if artist:
            self._writeLine(QString('PERFORMER "%1"').arg(artist))

        if songWriter:
            self._writeLine(QString('SONGWRITER "%1"').arg(songWriter))

        if album:
            self._writeLine(QString('TITLE "%1"').arg(album))

        if self._pregapFile:
            self._writeLine(QString('FILE "%1" WAVE').arg(QFileInfo(self._pregapFile).fileName()))
        else:
            self._writeLine(QString('FILE "%1" WAVE').arg(QFileInfo(firstTrack.resultFileName()).fileName()))

        cueTracks = self._disc.cueTracks()

        # Tracks ...........................
        prevIndex = TrackIndex('00:00:00')
        for i in range(0, tracks.count()):
            track = tracks[i]
            index0 = cueTracks[i].cueIndex0()
            index1 = cueTracks[i].cueIndex1()

            self._writeLine(QString('  TRACK %1 AUDIO').arg(i+1, 2, 10, QChar('0')))

            if track.flags():
                self._writeLine(QString('    FLAGS %1').arg(track.flags()))

            if track.isrc():
                self._writeLine(QString('    ISRC %1').arg(track.isrc()))

            if track.title():
                self._writeLine(QString('    TITLE "%1"').arg(track.title()))


            if i==0:
                if self._pregapFile:
                    self._writeLine(QString('    INDEX 00 %1').arg('00:00:00'))
                    self._writeLine(QString('FILE "%1" WAVE').arg(QFileInfo(track.resultFileName()).fileName()))
                    self._writeLine(QString('    INDEX 01 %1').arg('00:00:00'))
                else:
                    self._writeLine(QString('    INDEX 00 %1').arg('00:00:00'))
                    self._writeLine(QString('    INDEX 01 %1').arg(index1.asString()))

            else:
                if not index0.isNull():
                    idx0 =  index0 - prevIndex
                    self._writeLine(QString('    INDEX 00 %1').arg(idx0.asString()))

                prevIndex = index1
                self._writeLine(QString('FILE "%1" WAVE').arg(QFileInfo(track.resultFileName()).fileName()))
                self._writeLine(QString('    INDEX 01 %1').arg('00:00:00'))


            if genre == None and track.genre():
                self._writeLine(QString('    REM GENRE "%1"').arg(track.genre()))

            if year == None and track.year() > 1900:
                self._writeLine(QString('    REM DATE %1').arg(track.year()))

            if artist == None and track.artist():
                self._writeLine(QString('    PERFORMER "%1"').arg(track.artist()))

            if songWriter == None and track.songWriter():
                self._writeLine(QString('    SONGWRITER "%1"').arg(track.songWriter()))

        self._file.close();
